package com.core.shared;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Locale;

/**
 * Created by ky.chen on 2016/9/27.
 */
public class I18nUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext ac) {
        context = ac;
    }

    /**
     * 根据code获取国际化文本
     *
     * @param code           字符串在资源文件对应的key
     * @param defaultMessage 如果找不到，使用该默认值
     * @param locale         指定一个Locale
     * @return
     */
    public static String getMessage(String code, String defaultMessage, Locale locale) {
        if (locale.equals(Locale.SIMPLIFIED_CHINESE)) {
            locale = Locale.CHINESE;
        }
        return context.getMessage(code, null, defaultMessage, locale);
    }

    /**
     * 根据code获取国际化文本, 找不到，直接抛出异常
     *
     * @param code   字符串在资源文件对应的key
     * @param locale 指定一个Locale
     * @return
     */
    public static String getMessage(String code, Locale locale) {
        if (locale.equals(Locale.SIMPLIFIED_CHINESE)) {
            locale = Locale.CHINESE;
        }
        return context.getMessage(code, null, locale);
    }

    /**
     * 根据code获取国际化文本, 找不到，直接抛出异常.Locale来自HttpRequest
     *
     * @param code 字符串在资源文件对应的key
     * @return
     */
    public static String getMessageByRequest(String code) {
        return getMessage(code, WebUtil.getCurrentLocale());
    }

    /**
     * 根据code获取国际化文本, 找不到，直接抛出异常.Locale来自HttpRequest
     *
     * @param code
     * @param objects 资源占位符参数
     *                字符串在资源文件对应的key
     * @return
     */
    public static String getMessageByRequest(String code, Object... objects) {
        return context.getMessage(code, objects, WebUtil.getCurrentLocale());
    }
}